package eu.smoothit.sis.admin.backendBean;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.faces.model.SelectItem;

import eu.smoothit.sis.admin.backendBean.superclass.DataTableAbstract;
import eu.smoothit.sis.db.SisDAOFactory;
import eu.smoothit.sis.db.api.daos.ISwarmDAO;
import eu.smoothit.sis.db.impl.entities.SwarmEntityEntry;

public class IoPViewBean extends DataTableAbstract<SwarmEntityEntry> {
	// Properties
	// ---------------------------------------------------------------------------------
	private static final Integer DEFAULT_TOP_Number = 10;
	private SwarmEntityEntry searchExample;
	private Integer numberOfTop = DEFAULT_TOP_Number;
	private String selectedIoPParameter;
	private static Collection<SelectItem> IoPParameters;
	static {
		IoPParameters = new LinkedList<SelectItem>();
		IoPParameters.add(new SelectItem("numberOfLeechers"));
		IoPParameters.add(new SelectItem("numberOfSeeds"));
		IoPParameters.add(new SelectItem("downloadProgress"));
	}
	// define DAO
	private ISwarmDAO dataDAO = (ISwarmDAO) SisDAOFactory.getFactory()
			.createSwarmDAO();

	// initialization
	public IoPViewBean() {
		searchExample = new SwarmEntityEntry();
		actionLoad();
	}

	// getter && setter
	// ----------------------------------------------------------------------------------
	public Collection<SelectItem> getIoPParameters() {
		return IoPParameters;
	}

	public Integer getNumberOfTop() {
		return numberOfTop;
	}

	public void setNumberOfTop(Integer numberOfTop) {
		this.numberOfTop = numberOfTop;
	}

	public SwarmEntityEntry getSearchExample() {
		return searchExample;
	}

	public String getSelectedIoPParameter() {
		return selectedIoPParameter;
	}

	public void setSelectedIoPParameter(String selectedIoPParamter) {
		this.selectedIoPParameter = selectedIoPParamter;
	}

	public void setSearchExample(SwarmEntityEntry searchExample) {
		this.searchExample = searchExample;
	}

	// Form actions
	// ----------------------------------------------------------------------------------
	/**
	 * get top N entries based on selected filed
	 */
	public void actionFiltering() {
		dataTable.setRows(getNumberOfTop()); // top X
		sortField = getSelectedIoPParameter(); // "numberOfLeechers";

	}

	@Override
	public void actionSave() {
		List<SwarmEntityEntry> editItems = new ArrayList<SwarmEntityEntry>();
		for (int index = 0; index < dataList.size(); index++) {
			if (isEditModeRow(index)) {
				editItems.add(dataList.get(index));
			}
		}
		try {
			for (SwarmEntityEntry editItem : editItems) {
				if (editItem.getId() == 0)
					try {
						// id=0 stand for new added entry
						dataDAO.persist(editItem);
					} catch (Exception e) {
						setErrorMessage(e.getMessage() + " Cause: "
								+ e.getCause());
						e.printStackTrace();
						return;
					}
				else
					try {
						// otherwise, it is existing entry, update it.
						dataDAO.update(editItem);
					} catch (Exception e) {
						setErrorMessage(e.getMessage() + " Cause: "
								+ e.getCause());
						e.printStackTrace();
						return;
					}
			}
		} catch (Exception e) {
			setErrorMessage(e.getMessage() + " Cause: " + e.getCause());
			e.printStackTrace();
			return;
		}

		// Toggle edit mode and reload data.
		editMode = false;
		actionLoad();
	}

	@Override
	public void actionDelete() {
		// Get selected items.
		List<SwarmEntityEntry> deleteItems = new ArrayList<SwarmEntityEntry>();

		for (int index = 0; index < dataList.size(); index++) {
			if (isSelectedRow(index)) {
				deleteItems.add(dataList.get(index));
			}
		}
		if (deleteItems.isEmpty()) {
			setErrorMessage("Select at least one item to delete.");
			return;
		}
		try {
			for (SwarmEntityEntry deleteItem : deleteItems)
				dataDAO.remove(deleteItem);
		} catch (Exception e) {
			setErrorMessage(e.getMessage() + " Cause: " + e.getCause());
			e.printStackTrace();
			return;
		}
		// Reload data and go to first page.
		actionLoad();
		pageFirst();
	}

	@Override
	public void actionRefresh() {
		searchExample = new SwarmEntityEntry();
		super.actionRefresh();
	}

	@Override
	public void actionLoad() {
		boolean isQuestion = false;
		try {
			if (isSearchMode()) {
				SwarmEntityEntry question = new SwarmEntityEntry();
				Boolean availability = searchExample.getAvailability();
				Double downloadProgress = searchExample.getDownloadProgress();
				Long NrOfLeechers = searchExample.getNumberOfLeechers();
				Long NrOfLocalLeechers = searchExample
						.getNumberOfLocalLeechers();
				Long NrOfSeeds = searchExample.getNumberOfSeeds();
				Long NrOfLocalSeeds = searchExample.getNumberOfLocalSeeds();
				Double playBackProgress = searchExample.getPlaybackProgress();
				String torrentURL = searchExample.getTorrentURL();
				// full pattern TODO in this case, downloadProgress=0 is not
				// searchable
				if ((downloadProgress != null) && (downloadProgress != 0)) {
					question.setDownloadProgress(downloadProgress);
					isQuestion = true;
				}
				if (availability != null) {
					question.setAvailablity(availability);
					isQuestion = true;
				}
				if ((NrOfLeechers != null) && (NrOfLeechers != 0)) {
					question.setNumberOfLeechers(NrOfLeechers);
					isQuestion = true;
				} else
					searchExample.setNumberOfLeechers(null);// TODO why need set
				// to null?
				if (NrOfLocalLeechers != null) {
					question.setNumberOfLocalLeechers(NrOfLocalLeechers);
					isQuestion = true;
				}
				if ((NrOfSeeds != null) && (NrOfSeeds != 0)) {
					question.setNumberOfSeeds(NrOfSeeds);
					isQuestion = true;
				} else
					searchExample.setNumberOfSeeds(null);
				if (NrOfLocalSeeds != null) {
					question.setNumberOfLocalSeeds(NrOfLocalSeeds);
					isQuestion = true;
				}
				if (downloadProgress != null) {
					question.setPlaybackProgress(playBackProgress);
					isQuestion = true;
				}
				if (torrentURL != null
						&& torrentURL.toString().trim().length() == 0) {
					question.setTorrentURL(torrentURL);
					isQuestion = true;
				}
				if (isQuestion) {
					dataList = dataDAO.get(question);
					isQuestion = false;
				} else
					setErrorMessage("Please enter at least one keyword for searching");
			} else {
				dataList = dataDAO.getAll(); // list();
			}
		} catch (Exception e) {
			setErrorMessage(e.getMessage() + " Cause: " + e.getCause());
			e.printStackTrace();
			return;
		}
		actionSort(null);
	}

	/**
	 * overload actionAdd(E) as JSF web page allows methods without parameters
	 * only.
	 */
	public void actionAdd() {
		actionAdd(new SwarmEntityEntry());
	}


}
